package xmlParser;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

public class XMLTest {
	public static void main(String[] args) {
		String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
						"<result>" +
							"<header id=\"11\">head中国</header>" +
							"<body>" +
								"<name1>jack</name1>" + 
								"<name2>rose</name2>" + 
							"</body>" +
							"<footer>" +
								"<end>this is end 1</end>" +
								"<end>this is end 2</end>" +
								"<end>this is end 3</end>" +
								"<endall id=\"over\">this is end all</endall>" +
							"</footer>" +
						"</result>";
		SAXBuilder builder = new SAXBuilder(false);
		Document doc;
		try {
			doc = builder.build(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
			Element root = doc.getRootElement();
			List list = root.getChildren();
			//get attribute & value
			Element header = root.getChild("header");
			System.out.println("head attr:"+header.getAttributeValue("id"));
			System.out.println("head value:"+header.getValue());
			
			//get nodes & value
			Element body = root.getChild("body");
			List bodys = body.getChildren();
			for(int i=0;i<bodys.size();i++){
				Element e = (Element)bodys.get(i);
				System.out.println(e.getName() +"->"+e.getValue());
			}
			
			//sax parse, known path:/result/footer/end
			XMLParseUtil  xp = new XMLParseUtil(xml, "utf-8");
			List<SAXBean> list2 = xp.queryNodes("/result/footer/end"); 
			for(SAXBean bean : list2){
				System.out.println(bean.fValue);
			}
			System.out.println(xp.queryNodes("/result/footer/endall").get(0).getAttribute("id"));
			System.out.println(xp.queryNodes("/result/footer/endall").get(0).getText());
			
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
